<?php
require_once('functions/pageLoad.php');
loginRequired();

$user_session = explode("_", $_SESSION['user']);
$user_id = $user_session[0];
$page_title = 'My subscription';

// current subscription details
//Change By Vyas Ishan 24 May 2013 Task2 added the status field condition
	$sql = "SELECT subscriptions.id, subscriptions.cost, subscriptions.name, subscriptions.radius, subscription_expiration, subscription_id FROM tradesman 
			LEFT JOIN subscriptions ON tradesman.subscription_id = subscriptions.id 
			WHERE subscriptions.status = '1' AND user_id = '".$user_id."'";
	$query=mysql_query( $sql ) or die ("Error in query: $sql . " . mysql_error());
	$rs=mysql_fetch_assoc($query);
	$subscription_id = $rs['subscription_id'];
	$subscription_cost = $rs['cost'];
	$subscription_name = $rs['name'];
	$subscription_radius = $rs['radius'];
	$expires = ($subscription_id == '1') ? date("Y-m-d", mktime(0,0,0,date("m"), date("d"), date("Y"))) : $rs['subscription_expiration'];

	$days_left = ceil((strtotime($expires) - mktime()) / 86400);
	$days_left = ($days_left < 0) ? 0 : $days_left ;
	$paid_prorata = number_format(round((($subscription_cost / 365) * $days_left) * 100) / 100, 2, '.', '');

include "class.paypal.recurring.php";
$obj=new paypal_recurring;

$obj->environment = 'live';	// or 'beta-sandbox' or 'live'
$obj->paymentType = urlencode('Authorization');				// or 'Sale' or 'Order'

// Set request-specific fields.
$obj->startDate = urlencode(date("c", strtotime($expires)));
$obj->billingPeriod = urlencode("Year");				// or "Day", "Week", "SemiMonth", "Year"
$obj->billingFreq = urlencode("1");		// combination of this and billingPeriod must be at most a year
$obj->currencyID = urlencode('GBP');			// or other currency code ('GBP', 'EUR', 'JPY', 'CAD', 'AUD')

/* PAYPAL API  DETAILS */
$obj->API_UserName = urlencode($settings['paypal_api_username']);
$obj->API_Password = urlencode($settings['paypal_api_password']);
$obj->API_Signature = urlencode($settings['paypal_api_signature']);
$obj->API_Endpoint = "https://api-3t.paypal.com/nvp";

/*SET SUCCESS AND FAIL URL*/
$obj->returnURL = urlencode("http://".$settings['domain_name']."/my-subscription?complete=true");
$obj->cancelURL = urlencode("http://".$settings['domain_name']."/my-subscription?error=true");

if($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['plan_type'])){
//Change By Vyas Ishan 24 May 2013 Task2 added the status field condition
$sql = "SELECT cost FROM subscriptions WHERE status = '1' AND id = '".mysql_real_escape_string($_POST['plan_type'])."'";
$query=mysql_query( $sql ) or die ("Error in query: $sql . " . mysql_error());
$rs=mysql_fetch_assoc($query);

	$prorata = (ceil((($rs['cost'] / 365) * $days_left) * 100) / 100);
	$prorata = $prorata - $paid_prorata;
	$prorata = ($prorata < 1) ? 0 : $prorata;
	$prorata = number_format($prorata, 2, '.', '');


$obj->paymentAmount = urlencode($rs['cost']);
$obj->initialPayment = urlencode($prorata);

$_SESSION['prorata'] = $prorata;
$_SESSION['amt'] = $rs['cost'];
$_SESSION['plan_type'] = $_POST['plan_type'];

$obj->setExpressCheckout();

}

else{
$obj->paymentAmount = urlencode($_SESSION['amt']);
$obj->initialPayment = urlencode($_SESSION['prorata']);
}

if(isset($_GET['complete'])){

	$result = $obj->getExpressCheckout();
	
	if($result['status'] == 'success'){
	
	// cancel existing profile
	$sql = "SELECT paypal_profile_id FROM tradesman WHERE user_id = '".$user_id."'";
	$query=mysql_query( $sql ) or die ("Error in query: $sql . " . mysql_error());
	$rs=mysql_fetch_assoc($query);
	
	if(strlen($rs['paypal_profile_id']) > 0){
	$cancel_result = $obj->ManageRecurringPaymentsProfileStatus($rs['paypal_profile_id']);
	}

	// update active & subscription expiration
	
	if($subscription_id == '1'){
		$expiration_sql = ", subscription_expiration = '".date("Y-m-d", mktime(0,0,0,date("m"), date("d"), date("Y")+1))."'";
	}
	
	$sql = "UPDATE tradesman SET paypal_profile_id = '".mysql_real_escape_string($result['profile_id'])."', subscription_id = '".mysql_real_escape_string($_SESSION['plan_type'])."'".$expiration_sql." WHERE user_id = '".$user_id."'";
	$query=mysql_query( $sql ) or die ("Error in query: $sql . " . mysql_error());
	
	// insert payment
	$sql = "SELECT id FROM tradesman WHERE user_id = '".mysql_real_escape_string($user_id)."'";
	$query=mysql_query( $sql ) or die ("Error in query: $sql . " . mysql_error());
	$rs=mysql_fetch_assoc($query);

	$payment_sql = "INSERT INTO payments SET user_id = '".mysql_real_escape_string($user_id)."', tradesman_id = '".$rs['id']."', payment_type = '2', amount = '".$_SESSION['amt']."', ip_address = '".$_SERVER['REMOTE_ADDR']."', payment_made = NOW()";
	$payment_query=mysql_query( $payment_sql ) or die ("Error in query: $payment_sql . " . mysql_error());	

	$upgrade_results = '<div class="yellow_box"><p>Thank you, your subscription has been upgraded.</p></div>';
	
	}

}

	// upgrade options
	
	$js = '';
	$i = 0;
	//Change By Vyas Ishan 24 May 2013 Task2 added the status field condition
	$pp_sql = "SELECT id, radius, cost FROM subscriptions WHERE   status='1' and  cost > '".$subscription_cost."' ORDER BY cost";
	$pp_query=mysql_query( $pp_sql ) or die ("Error in query: $pp_sql . " . mysql_error());
	$pp_rows = mysql_num_rows($pp_query);
	
	while($pp_rs=mysql_fetch_assoc($pp_query)){
	
	$upgrade_options.='<option value="'.$pp_rs['id'].'">'.$pp_rs['radius'].' miles - &pound;'.$pp_rs['cost'].' per year</option>';

	$prorata = (ceil((($pp_rs['cost'] / 365) * $days_left) * 100) / 100);
	$prorata = $prorata - $paid_prorata;
	$prorata = ($prorata < 1) ? 0 : $prorata;
	$prorata = number_format($prorata, 2, '.', '');
	
	$js.='
	radius_arr['.$pp_rs['id'].'] = \''.$pp_rs['radius'].'\';
	prorata_arr['.$pp_rs['id'].'] = \''.$prorata.'\';
	annual_arr['.$pp_rs['id'].'] = \''.$pp_rs['cost'].'\';
	';
	
	if($i == 0){
	$first_upgrade = array('prorata' => $prorata, 'radius' => $pp_rs['radius'], 'annual' => $pp_rs['cost']);
	}
	
	$i++;
	}
	
	$additionalMeta = '<script type="text/javascript">

var radius_arr = new Array();
var prorata_arr = new Array();
var annual_arr = new Array();
'.$js.'

function update_upgrade_txt(){
	var plan_type = parseFloat(document.getElementById(\'plan_type\').value);
	document.getElementById(\'radius\').innerHTML = radius_arr[plan_type];
	document.getElementById(\'prorata\').innerHTML = prorata_arr[plan_type];
	document.getElementById(\'annual\').innerHTML = annual_arr[plan_type];
}
</script>';

include('includes/meta.php');
include('includes/header.php');
include('includes/navigation.php');

?>

<h1><?php echo $page_title; ?></h1>

<?php echo $upgrade_results; ?>

<p><strong>You are currently on the <?php echo $subscription_name; ?> subscription with a <?php echo $subscription_radius; ?> mile radius, which costs &pound;<?php echo $subscription_cost; ?> per year and is due for renewal on <?php echo date("d/m/Y", strtotime($expires)); ?>.</strong></p>

<?php if($pp_rows > 0){ ?>

<p><strong>You can upgrade your subscription and increase your radius at any time by choosing from the options below. If you would like to cancel your subscription and terminate your account, please <a href="/cancel-subscription">click here</a>.</strong></p>

<form method="post" action="">

<div class="rowWrapper">
<div class="rowLeft"><label for="plan_type">New radius:</label></div>
<div class="rowRight">
<select id="plan_type" name="plan_type" onchange="update_upgrade_txt();">
<?php echo $upgrade_options; ?>
</select>
</div>
</div>

<p><strong>Upgrading your radius to <span id="radius"><?php echo $first_upgrade['radius']; ?></span> miles will require a one-off pro-rata payment of &pound;<span id="prorata"><?php echo $first_upgrade['prorata']; ?></span> and an annual subscription of &pound;<span id="annual"><?php echo $first_upgrade['annual']; ?></span>. To upgrade, click the button below. You will be forwarded to PayPal for secure payment and subscription authorisation.</strong></p>

<input type="image" src="/images/upgrade_button.png" alt="Upgrade">

</form>

<?php } else{ ?>

<p><strong>You're currently on our top package and no upgrades are available at this time. If you would like to cancel your subscription and terminate your account, please <a href="/cancel-subscription">click here</a>.</strong></p>

<?php } ?>

</div>



<?php 

include('includes/rightColumn.php');
include('includes/footer.php');

?>